/**
 * Spring board基类. 
 * @param {Object} $wrapper
 * @param {Object} cardTmp
 */
function CardList($wrapper, cardTmp){    
    var _this = this;    
    Observable.enable(this);
    
    this.$wrapper = $wrapper;
    this.cardTmp = cardTmp;
    
    var cardItemEventMapping = {
        'deleteItem' : '.cardCloseBtn',
        'editItem' : '.edit',
        'showReport' : '.report',
        'cardIconClick' : '.cardWrapper .cardIcon',
        'dblclick' : '.cardWrapper|dblclick'    
    };
    
    Object.each(cardItemEventMapping, function(eventName, jQuerySelector){
        jQuerySelector = jQuerySelector.split('|');
        _this.$wrapper.delegate(jQuerySelector[0], jQuerySelector[1] || 'click', function() {
            var $cardItem = $(this).closest('.cardWrapper');
            _this.fire(eventName, $cardItem.attr('card-id'), $cardItem, _this);       
            return false; 
        });
    });
    
    this.$itemAdder = $('<div class="itemAdder"></div>');
    this.$itemAdder.appendTo(this.$wrapper);
    
    this.store = new Store();
    this.store.on('addItem', function(item){
        _this.load([item]);
    });    
    this.store.on('updateItem', function(item){
        _this.load([item]);
    });
}

CardList.prototype.load = function(data){
    for(var i=0; i<data.length; i++){        
        var $existedItem = this.$wrapper.find('.cardWrapper[card-id={0}]'.format(data[i]['id']));
        var newItemHtml = tmpl(this.cardTmp, data[i]);
        if($existedItem.isExist()){
            $existedItem.replaceWith(newItemHtml);
        } else {
            this.addOrderly(newItemHtml);
        }
    }
};


CardList.prototype.addOrderly = function($item){
    $item = $($item);    
    var lastdotime = $item.find('.cardName').text().trim();
    
    var $sessionListItems = this.$wrapper.find('.cardWrapper');
    if(!$sessionListItems.length){
        this.$wrapper.append($item);
        return this;
    } else {
        for(var i=0; i<$sessionListItems.length; i++){
            var $cur = $($sessionListItems.get(i));
            var nowTime = $cur.find('.cardName').text().trim();
            if(lastdotime < nowTime){
                $cur.before($item);
                return this;
            }
        }
    }
    
    this.$wrapper.append($item);
    return this;
};

CardList.prototype.addItem = function(chatCfg){
    var _this = this;
    this.store.addItem(chatCfg);
};

CardList.prototype.deleteItem = function($cardItem){
    if(Type.isString($cardItem)){
        var cardID = $cardItem;
        return this.deleteItem(this.$wrapper.find('.cardWrapper[card-id={0}]'.format(cardID)));
    }
    $cardItem.animate({
        scale : 0.1
    }, 500, function() {
        $(this).remove();
    });  
};